package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl.task;

import com.alibaba.fastjson.JSON;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ResolveCandidateService;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.TaskCreatedPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.exception.EventCallSuspendException;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.task.FlowTaskInstApproverVo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.userentity.UserInfo;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTaskInstApproverRepository;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.identitylink.service.impl.persistence.entity.IdentityLinkEntity;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author: niechanggang
 * @date:2021/9/2 10:04
 * @description:  保存任务实例对应的审批人
 */
@Service
@Order(20)
public class SaveTaskInstApproverPostProcessor  implements TaskCreatedPostProcessor {

    private Logger  logger  = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private FlowTaskInstApproverRepository  flowTaskInstApproverRepository;

    @Autowired
    private ResolveCandidateService resolveCandidateService;

    @Override
    public void process(TaskEntity taskEntity) throws EventCallSuspendException {
        Set<String> userIds = new HashSet<>();
        List<IdentityLinkEntity> identityLinkEntityList = taskEntity.getIdentityLinks();

        if (CollectionUtils.isNotEmpty(identityLinkEntityList)){
            for (IdentityLinkEntity identityLinkEntity : identityLinkEntityList) {
                //删除的不计算
                if (identityLinkEntity.isDeleted()){
                    continue;
                }
                String type = identityLinkEntity.getType();
                String userId = identityLinkEntity.getUserId();
                String groupId = identityLinkEntity.getGroupId();
                if (StringUtils.isNotBlank(userId)){
                    userIds.add(userId);
                }

                if (StringUtils.isNotBlank(groupId)){
                    List<UserInfo> userInfoList = resolveCandidateService.getUserInfoByCode(type,groupId,null);
                    if (CollectionUtils.isNotEmpty(userInfoList)){
                        for (UserInfo userInfo : userInfoList) {
                            userIds.add(userInfo.getUserCode());
                        }
                    }
                }
            }
        }
        if(StringUtils.isNotEmpty(taskEntity.getAssignee())  ){
            userIds.add(taskEntity.getAssignee());
        }
        this.saveTaskInstApprover(taskEntity.getId(), userIds);
    }


    private void saveTaskInstApprover(String taskId, Set<String> userIds) {
        logger.error("SaveTaskInstApprover:" + JSON.toJSONString(userIds));
        for (String userId : userIds) {
            try {
                FlowTaskInstApproverVo flowTaskInstApproverVo = new FlowTaskInstApproverVo();
                flowTaskInstApproverVo.setTaskId(taskId);
                flowTaskInstApproverVo.setUserId(userId);
                flowTaskInstApproverVo.setCreateTime(new Date());
                flowTaskInstApproverRepository.insert(flowTaskInstApproverVo);
                logger.info("插入数据表【flow_task_inst_approver】成功,taskId:" + taskId + ",userId:" + userId);
            } catch (Exception ex) {
                logger.error("insert into flow_task_inst_approver error", ex);
                continue;
            }
        }
    }

}
